<template>
	<view id="mapContainer" :prop="[tk,pageData,mapSelect]" :change:prop="mapModule.update">
		<view class="container">
			<view class="left" @click="handleImageClick">
			</view>
			<view class="right">
				<uni-data-select v-model="mapSelect" :localdata="mapList" :clear="false"
					style="width: 120px;"></uni-data-select>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		getAuthorization
	} from '@/router/auth.js'
	import {
		pageRiskLocation,
		pictureList
	} from '@/api/riskcontrol.js'
	export default {
		data() {
			return {
				tk: '',
				queryParams: {
					pageNum: 1,
					pageSize: 100,
				},
				pageData: null,
				mapList: [],
				mapSelect: ''
			}
		},
		mounted() {
			const token = getAuthorization('accessToken')
			this.tk = token
			pageRiskLocation(this.queryParams).then(res => {
				this.pageData = res.data?.rows
			})
			pictureList().then(res => {
				res.data.map((item) => {
					if (item.isShow == 1) {
						this.mapList = [{
							text: item.pictureName,
							value: item.id
						}]
						this.mapSelect = item.id
					}

				})
			})
		},
		methods: {
			onMarkClick(val) {
				// #ifdef APP-PLUS
				plus.screen.unlockOrientation()
				plus.screen.lockOrientation('portrait-primary');
				// #endif
				uni.navigateTo({
					url: '/pages/professional/secure/mapPage?riskLocationId=' + JSON.stringify(val)
				})
			},
			handleImageClick() {
				// #ifdef APP-PLUS
				plus.screen.unlockOrientation()
				plus.screen.lockOrientation('portrait-primary');
				// #endif
				uni.navigateBack({
					delta: 1 // 返回的页面数，如果是1则返回上一页
				})
			}
		},
		onShow() {
			// 页面每次出现在屏幕上 自动切换成固定横屏
			setTimeout(() => {
				// #ifdef APP-PLUS
				plus.screen.lockOrientation("landscape-primary");
				// #endif
			}, 100)
		},
		onUnload() {
			// #ifdef APP-PLUS
			plus.screen.unlockOrientation()
			plus.screen.lockOrientation('portrait-primary');
			// #endif
		}
	}
</script>
<script module="mapModule" lang="renderjs">
	import L from 'leaflet';
	export default {
		data() {
			return {
				map: null,
				flag: true,
				baseUrl: 'http://172.16.30.75:8888/api/min/picture/getMineHome',
				mapSelect: '',
				isShow: false
			};
		},
		mounted() {
			this.initMap();
			// console.log('mounted');
		},
		beforeDestroy() {
			this.map?.remove()
		},
		methods: {
			initMap() {
				this.map = L.map('mapContainer', {
					zoomControl: false
				}).setView([44.522, 90.4205], 13);
			},
			getMap(tk) {
				this.flag = false
				const params = {
					id: this.mapSelect
				};
				const urlParams = `${this.baseUrl}?${new URLSearchParams(params)}`;
				fetch(urlParams, {
					method: 'get',
					headers: {
						Authorization: 'Bearer ' + tk
					}
				}).then(async (response) => {
					const res = await response.json()
					const features = res.data;
					if (features.length) {
						for (let i = 0; i < features.length; i++) {
							const feature = features[i];
							const path = feature.path;
							const polylinePoints = path.map(([lng, lat]) => L.latLng(lat, lng));
							const polyline = L.polyline(polylinePoints, {
								weight: 1,
								color: '#fff',
							});
							polyline.addTo(this.map);
							i === features.length - 1 ? this.isShow = true : ''
						}
					}
				}).catch(() => {
					this.isShow = false
				})
			},
			mapLayer(data) {
				data.map(item => {
					// 根据颜色选择图标
					const icon = L.icon({
						iconUrl: item.color == 'red' ? '/static/img/map/red.png' : item.color == 'orange' ?
							'/static/img/map/orange.png' : item.color == 'yellow' ?
							'/static/img/map/yellow.png' : item
							.color == 'blue' ? '/static/img/map/blue.png' : '',
						iconSize: [23, 23],
						iconAnchor: [18, 36],
						popupAnchor: [0, -30]
					});

					function swapElements(arr) {
						if (arr.length >= 2) {
							[arr[0], arr[1]] = [arr[1], arr[0]];
						}
						return arr;
					}

					function swapSubarrays(arr) {
						for (let i = 0; i < arr.length; i++) {
							if (arr[i].length >= 2) {
								[arr[i][0], arr[i][1]] = [arr[i][1], arr[i][0]];
							}
						}
						return arr;
					}
					let that = this
					// 创建Marker或Polygon的相关逻辑
					if (item.riskAreaLonLatType == 0) {
						let marker = L.marker(item.riskAreaCenterLon ? swapElements(JSON.parse(item
							.riskAreaCenterLon)) : '', {
							icon: icon,
						}).addTo(this.map).bindPopup(item.riskLocationName);
						marker.on('click', function() {
							that.$ownerInstance.callMethod('onMarkClick', item.riskLocationId)
						});
					} else if (item.riskAreaLonLatType == 1) {
						let polygon = L.polygon(item.riskAreaLonLatJson ? swapSubarrays(JSON.parse(item
							.riskAreaLonLatJson)) : '', {
							color: item.color,
							fillColor: item.color,
						}).addTo(this.map).bindPopup(item.riskLocationName);
						polygon.on('click', function() {
							that.$ownerInstance.callMethod('onMarkClick', item.riskLocationId)
						});
					}
				});
			},
			update(newValue) {
				newValue[2] ? this.mapSelect = newValue[2] : ''
				newValue[1] && this.isShow ? this.mapLayer(newValue[1]) : ''
				this.mapSelect ? this.flag && this.getMap(newValue[0]) : ''
			},
		},
	};
</script>
<style scoped>
	#mapContainer {
		padding: 0;
		margin: 0;
		height: 100vh;
		background-color: #10172d;
	}

	.container {
		width: 95%;
		height: 23px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px;
		background-color: transparent;
		position: fixed;
		left: 0px;
		top: 30px;
		z-index: 9999;
	}

	.left {
		width: 35px;
		height: 35px;
		cursor: pointer;
		margin-left: 15px;
		background-image: url('/static/img/tc.png');
		background-size: cover;
	}
</style>